package com.ccp.dev.form.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.model.FormDef;
import com.ccp.dev.form.model.FormField;
import com.ccp.dev.form.model.FormTable;
import com.ccp.dev.form.model.PrintTemplate;
import com.ccp.dev.form.service.FormDefService;
import com.ccp.dev.form.service.FormFieldService;
import com.ccp.dev.form.service.FormTableService;
import com.ccp.dev.form.service.PrintTemplateService;
import com.ccp.dev.form.util.FormUtil;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务打印模板控制器类
 *
 * @author chenjing
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_FORM + "/printTemplate")
@Action(ownermodel = SysAuditModelType.FORM_MANAGEMENT)
public class PrintTemplateController extends SysBaseController {

    @Resource
    private PrintTemplateService printTemplateService;

    @Resource
    private FormTableService formTableService;

    @Resource
    private FormDefService formDefService;

    /**
     * 跳转 编辑打印模版页面
     *
     * @param request request
     * @param modelMap modelMap
     * @return String
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/formDesign/printFormDevise")
    @Action(description = "表单打印模板编辑打印模版页面跳转",exectype = "页面跳转日志")
    public String editView(HttpServletRequest request, ModelMap modelMap){
        String id = RequestUtil.getString(request, "id");
        String formKey = RequestUtil.getString(request, "formKey");
        FormDef formDef=formDefService.getDefaultVersionByFormKey(formKey);
        modelMap.put("id",id);
        modelMap.put("formKey",formKey);
        modelMap.put("formDefId",formDef.getFormDefId());
        modelMap.put("tableId",formDef.getTableId());
        return "/form/formDef/formDesign/printFormDevise";
    }

    /**
     * 跳转 左侧模板页面
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/formDesign/printFormLeftTem")
    @Action(description = "表单打印模板左侧模板页面跳转",exectype = "页面跳转日志")
    public String formLeftTem(HttpServletRequest request, ModelMap modelMap) {
        String formDefId = RequestUtil.getString(request, "formDefId");
        modelMap.put("formDefId", formDefId);
        return "/form/formDef/formDesign/printFormLeftTem";
    }

    /**
     * 跳转 预览打印模版页面
     *
     * @param request request
     * @param modelMap modelMap
     * @return html
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/formDesign/printFormPreview")
    @Action(description = "表单打印模板预览页面跳转",exectype = "页面跳转日志")
    public String getView(HttpServletRequest request,ModelMap modelMap){
        String printTemplateId = RequestUtil.getString(request, "printTemplateId");
        modelMap.put("printTemplateId",printTemplateId);
        return "/form/formDef/formDesign/printFormPreview";
    }

    /**
     * 获取表单对应打印模板列表
     * @param request request
     * @return 打印模板列表
     */
    @RequestMapping("/list")
    @ResponseBody
    @Action(description = "表单打印模板列表",exectype = "查询日志",detail = "查询表单打印模板列表<#if success>成功<#else>失败</#if>")
    public ResultData list(HttpServletRequest request){
        QueryFilter queryFilter=new QueryFilter(request,true);
        String formKey= RequestUtil.getString(request,"formKey");
        queryFilter.put("formKey",formKey);
        try {
            List<PrintTemplate> list = printTemplateService.queryList(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success", queryFilter.getPageBean().getTotalCount(), list);
        }catch (Exception e){
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 删除打印模版
     *
     * @param request request
     * @return msg
     */
    @RequestMapping("/del")
    @ResponseBody
    @Action(description = "删除表单打印模板",exectype = "删除日志",detail = "删除表单打印模板<#if success>成功<#else>失败</#if>")
    public ResultData del(HttpServletRequest request) {
        try {
            String id = RequestUtil.getString(request, "id");
            printTemplateService.delByPrintId(id);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("delete.success");
        } catch (Exception ex) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 编辑打印模版
     *
     * @param request request
     * @return printTemplate
     */
    @RequestMapping("/edit")
    @ResponseBody
    @Action(description = "编辑表单打印模板",exectype = "编辑日志",detail = "编辑表单打印模板<#if success>成功<#else>失败</#if>")
    public ResultData edit(HttpServletRequest request){
        String id = RequestUtil.getString(request, "id");
        String formKey = RequestUtil.getString(request, "formKey");

        Map<String, Object> retMap = new HashMap<>(16);
        try {
            if (StringUtil.isNotEmpty(formKey)) {
                FormDef formDef=formDefService.getDefaultVersionByFormKey(formKey);
                PrintTemplate printTemplate=new PrintTemplate();
                if (StringUtil.isEmpty(id)) {
                    printTemplate.setHtml(formDef.getHtml());
                    printTemplate.setTemplateName(formDef.getSubject());
                } else {
                    printTemplate = printTemplateService.getOneById(id);
                }
                retMap.put("printTemplate", printTemplate);
                retMap = formDefService.getEditDataByFormDef(formDef,retMap);
            }
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success",retMap);
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 添加或更新表单模板。
     * @param printTemplate 添加或更新的实体
     * @return msg
     */
    @RequestMapping("/add")
    @ResponseBody
    @Action(description = "添加或更新表单打印模板",exectype = "添加或更新日志",detail = "添加或更新表单打印模板<#if success>成功<#else>失败</#if>")
    public ResultData save(@RequestBody PrintTemplate printTemplate) {
        String html=printTemplate.getHtml();
        String tableId=printTemplate.getTableId();
        FormTable formTable=formTableService.getOneById(tableId);
        String tableName=formTable.getTableName();
        String tableComment=formTable.getTableDesc();
        String template= FormUtil.getPrintFreeMarkerTemplate(html,tableName,tableComment);
        printTemplate.setTemplate(template);
        //判断别名是否存在
        boolean isExist=printTemplateService.isExistAlias(printTemplate.getAlias(),printTemplate.getId());
        String resultMsg;
        if(isExist){
            resultMsg="printTemplate.alias.exist";
            return getResultDataError(resultMsg);
        }
        if(StringUtil.isEmpty(printTemplate.getId())){
            resultMsg="printTemplate.add.success";
        }else {
            resultMsg="printTemplate.update.success";
        }
        try {
            printTemplateService.save(printTemplate);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess(resultMsg);
        }catch (Exception e){
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("save.failure");
        }
    }

    /**
     * 预览打印模版
     *
     * @param request request
     * @return html
     */
    @RequestMapping("/get")
    @ResponseBody
    @Action(description = "表单打印模板预览",exectype = "查询日志",detail = "表单打印模板预览<#if success>成功<#else>失败</#if>")
    public ResultData get(HttpServletRequest request){
        String id = RequestUtil.getString(request, "id");
        try {
            PrintTemplate printTemplate = printTemplateService.getOneById(id);
            String html = "";
            if (printTemplate != null) {
                html = printTemplate.getHtml();
            }
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success", html);
        }catch (Exception e){
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 设置默认打印模板
     * @param request request
     * @return msg
     */
    @RequestMapping("/setDefault")
    @ResponseBody
    @Action(description = "表单打印模板设置默认版本",exectype = "更新日志",detail = "表单打印模板设置默认版本<#if success>成功<#else>失败</#if>")
    public ResultData setDefault(HttpServletRequest request){
        String id = RequestUtil.getString(request, "id");
        String formKey = RequestUtil.getString(request, "formKey");
        try {
            printTemplateService.setDefault(id, formKey);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("printTemplate.setDefault.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("printTemplate.setDefault.failure");
        }
    }
}
